<?php
namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Laravel\Lumen\Routing\Controller;
use Vinkla\Hashids\Facades\Hashids;

class CheckController extends Controller {
	public $res = array();
	public $userinfo = '';
	protected $bmsApiUtil;
	// token获取openid 判断token是否失效
	public function __construct(Request $request) {
		$token = $request->input('token', '');
		if ($token && Cache::has($token.'openid')) {
			$this->res = array(
				"meta" => array("code"=>200,"message"=>''),
				"data" => array()
			);
			$openid = Cache::get($token.'openid');
			$user = User::where('openid', $openid)->first();
			if ($user) {
				$this->userinfo = $user;
			} else {
				$this->res = array(
					"meta" => array("code"=>400,"message"=>'用户不存在'),
					"data" => array()
				);
				echo json_encode($this->res);
				die();
			}
		} else {
			$this->res = array(
				"meta" => array("code"=>400,"message"=>'登录超时'),
				"data" => array()
			);
			echo json_encode($this->res);
			die();
		}
	}

	/**
	 * api统一出口
	 *
	 * @param  string  $code
	 * @param  string  $message
	 * @param  array   $data
	 * @return json
	 */
	public function output($code = "200",$message = "",$data = array(),$jsonp='') {
		$res = array(
				"meta" => array("code"=>$code,"message"=>$message),
				"data" => $data
			);
		if(!$jsonp){
			return response()->json($res);
		}
		else{
			return response()->json($res)->setCallback($jsonp);
		}
	}

    // 发起外部网络请求
    public function sendRequest($url, $option = array(), $header = array(), $type = 'POST') {
        $curl = curl_init (); // 启动一个CURL会话
        curl_setopt ( $curl, CURLOPT_URL, $url ); // 要访问的地址
        curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, FALSE ); // 对认证证书来源的检查
        curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, FALSE ); // 从证书中检查SSL加密算法是否存在
        curl_setopt ( $curl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)' ); // 模拟用户使用的浏览器
        if(!empty($option)){
            $options = json_encode ( $option ,JSON_UNESCAPED_UNICODE);
            curl_setopt ( $curl, CURLOPT_POSTFIELDS, $options ); // Post提交的数据包
        }
        if(empty($header)){
            $header = array('Content-Type: application/json');
        }
        curl_setopt ( $curl, CURLOPT_TIMEOUT, 30 ); // 设置超时限制防止死循环
        curl_setopt ( $curl, CURLOPT_HTTPHEADER, $header ); // 设置HTTP头
        curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 ); // 获取的信息以文件流的形式返回
        curl_setopt ( $curl, CURLOPT_CUSTOMREQUEST, $type );
        $result = curl_exec ( $curl ); // 执行操作
        $result = json_decode($result);
        curl_close ( $curl ); // 关闭CURL会话
        return $result;
    }
}
